require 'rubygems'
require 'facets/core/enumerable/sum'

module Yahtzee

  class Dice
  	include Enumerable

	  def initialize(all = {}, die_count = 6)
	    @all = all
	    @die_count = die_count
	    (1..@die_count).each { |x| @all[x] = 0 } if @all.size == 0
	  end
	
	  def roll(keep = [])
	    (1..@die_count).each { |x| @all[x] = 0 if !keep.include? x }
	    num_to_roll = @die_count - @all.values.sum
	    num_to_roll.times { @all[(rand(6) + 1)] += 1 }
	    rank_result
	  end
	  
	  def to_hash
	    Hash.new().merge!(@all)
	  end
	
	  def max_die
	    max = @all.values.max
	    @all.delete_if { |k,v| v < max }
	  end
	
	  def die_count(die)
	    if @all.include? die
	      @all[die] 
	    else
	      0
	    end
	  end
	
	  def yahtzee?
	    @all.each do |die,num_rolled|
	      return true if num_rolled == @die_count 
	    end
	    return false
	  end
	
	  def rank_result
	     result = {}
	     @all.each do |die,num_rolled|
	       if result[num_rolled].nil?
	          result[num_rolled] = [die]
	       else
	          result[num_rolled] << die
	       end
	     end
	     result
	  end
  end
end